<?php
namespace app;
use think\App;
use think\contract\LogHandlerInterface;
use think\event\LogRecord;
class TLogHandler implements LogHandlerInterface
{

    /**
     * 配置参数
     * @var array
     */
    protected $config = [
        'time_format'  => 'c',
        'file_size'    => 2097152,
        'path'         => '',
        'max_files'    => 0,
        'json'         => true,
        'json_options' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
        'format'       => '[%s][%s] %s',
    ];

    // 实例化并传入参数
    public function __construct(App $app, $config = [])
    {

        if (is_array($config)) {
            $this->config = array_merge($this->config, $config);
        }

        if (empty($this->config['format'])) {
            $this->config['format'] = '[%s][%s] %s';
        }

        if (empty($this->config['path'])) {
            $this->config['path'] = $app->getRuntimePath() . 'log';
        }

        if (substr($this->config['path'], -1) != DIRECTORY_SEPARATOR) {
            $this->config['path'] .= DIRECTORY_SEPARATOR;
        }
    }

    /**
     * 日志写入接口
     * @access public
     * @param array<LogRecord> $log 日志信息
     * @return bool
     */
    public function save(array $log): bool
    {
        $messages = [];
        // 日志信息封装
        foreach ($log as  $record) {
            $message = $this->initLog();
            $message["time"] = $record->time->format($this->config['time_format']);
            $type = $record->type;
            $msg = $record->message;
            $destination = $this->getMasterLogFile($type);
            if (!is_string($msg)) {
                $msg = var_export($msg, true);
            }
            if ($this->config['json']) {
                $message["msg"] = $msg;
                $tmpMsg = json_encode($message, $this->config['json_options']);
            } else {
                $str = " ";
                foreach ($message as $key => $value) {
                    $str .= "$key" . '[' . $value . '] ';
                }
                $str.=$msg;
                $tmpMsg = date("Y-m-d H:i:s").$str.PHP_EOL;
            }
            $messages[$destination][] = $tmpMsg;
        }
        foreach ($messages as $filename => $message) {
            $this->write($message, $filename);
        }
        return true;
    }


    /**
     * 日志写入
     * @access protected
     * @param array  $message     日志信息
     * @param string $destination 日志文件
     * @return bool
     */
    protected function write(array $message, string $destination): bool
    {
        // 检测日志文件大小，超过配置大小则备份日志文件重新生成
        $this->checkLogSize($destination);

        return error_log(implode(PHP_EOL, $message) . PHP_EOL, 3, $destination);
    }
    /**
     * 获取主日志文件名
     * @access public
     * @return string
     */
    protected function getMasterLogFile($type): string
    {

        if ($this->config['max_files']) {
            $fileName = sprintf("%s%s.log.*", $this->config['path'], $type);
            $files = glob($fileName);
            try {
                if (count($files) > $this->config['max_files']) {
                    set_error_handler(function ($errno, $errstr, $errfile, $errline) {
                    });
                    unlink($files[0]);
                    restore_error_handler();
                }
            } catch (\Exception $e) {
                //
            }
        }
        $filename =  sprintf("%s.%s.%s",$type,"log",date("Y-m-d-H"));
        $destination = $this->config['path'] . $filename;
        $path = dirname($destination);
        !is_dir($path) && mkdir($path, 0755, true);
        return $destination;
    }



    /**
     * 检查日志文件大小并自动生成备份文件
     * @access protected
     * @param string $destination 日志文件
     * @return void
     */
    protected function checkLogSize(string $destination): void
    {
        if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) {
            try {
                rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . basename($destination, '.log') . '-' . time() . '.log');
            } catch (\Exception $e) {
                //
            }
        }
    }

    /**
     * 增加日志参数
     * @return array
     */
   protected   function initLog()
    {

        if (php_sapi_name()!="cli") {
            $requrest = request();
            $notice =[
                "log_id"=>create_log_id(),
                "module_id"=>app('http')->getName(),
                "client_ip"=>$requrest->ip(),
                "url"=>$requrest->url(),
                "server_ip"=>$_SERVER["SERVER_ADDR"] ?? $_SERVER["SERVER_ADDR"],
                "user_agent"=>$_SERVER["HTTP_USER_AGENT"] ?? $_SERVER["HTTP_USER_AGENT"]
            ];
        } else {
            $notice =[
                "log_id"=>create_log_id(),
                "module_id"=>"",
                "client_ip"=>"127.0.0.1",
                "server_ip"=>gethostbyname(gethostname()),
                "url"=>$_SERVER["SCRIPT_FILENAME"],
                "user_agent"=>json_encode($_SERVER["argv"])
            ];
        }
        return $notice;
    }

}